package com.gaff.emp.core.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisUtil {

    private static RedisTemplate<String, String> redisTemplate;

    private final static long NOT_EXPIRE = -1;

    public static void set(String key, Object value) {
        set(key, value, NOT_EXPIRE);
    }

    public static void set(String key, Object value, long expire) {
        try {
            if (expire != NOT_EXPIRE) {
                getRedisTemplate().opsForValue().set(key, JSON.toJSONString(value), expire, TimeUnit.MILLISECONDS);
            } else {
                getRedisTemplate().opsForValue().set(key, JSON.toJSONString(value));
            }
        } catch (Exception e) {
            log.error("RedisUtil.set() error", e);
        }
    }

    public static <T> T get(String key, Class<T> clazz) {
        try {
            String value = getRedisTemplate().opsForValue().get(key);
            return value == null ? null : JSON.parseObject(value, clazz);
        } catch (Exception e) {
            log.error("RedisUtil.get() error", e);
            return null;
        }
    }

    public static void delete(String key) {
        try {
            getRedisTemplate().delete(key);
        }catch (Exception e){
            log.error("RedisUtil.delete() error", e);
        }
    }

    private static RedisTemplate<String, String> getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate<String, String>) ContextUtil.getBean(RedisTemplate.class);
        }
        return redisTemplate;
    }

}
